#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int g_tmp = 1;

pthread_rwlock_t g_lock;

void* my_thread_start(void* arg){
    while(1){
        pthread_rwlock_rdlock(&g_lock);
        printf("i am %p, g_tmp is %d\n", pthread_self(), g_tmp);
        sleep(10000);
        pthread_rwlock_unlock(&g_lock);
    }
}

void* my_thread_start_wr(void* arg){
        pthread_rwlock_wrlock(&g_lock);
        g_tmp = 2;
        pthread_rwlock_unlock(&g_lock);
}

int main(){
    pthread_rwlock_init(&g_lock, NULL);

    pthread_t tid[2];
    for(int i = 0; i < 2; i++){
        int ret = pthread_create(&tid[i], NULL, my_thread_start, NULL);
        if(ret < 0){
            return 0;
        }
    }
    sleep(1);

    pthread_t wr_tid;
    int ret = pthread_create(&wr_tid, NULL, my_thread_start_wr, NULL);
    if(ret < 0){
        return 0;
    }


    for(int i = 0; i < 2; i++){
        pthread_join(tid[i], NULL);
    }
    pthread_join(wr_tid, NULL);
    pthread_rwlock_destroy(&g_lock);
    return 0;
}
